package org.blog.servlets;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.blog.beans.User;
import org.blog.controller.UserController;
import org.blog.exceptions.InvalidMailException;
import org.blog.exceptions.SettingsException;
import org.blog.logic.UserLogic;
import org.blog.messages.UserSettingsMessage;

/**
 * Servlet implementation class UserSettings
 */
public class UserSettings extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserSettings() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}
	
	private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		if("save".equals(request.getParameter("do"))) {
			
			User user = new User();
					
			try {
				BeanUtils.populate(user, request.getParameterMap());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			UserSettingsMessage usm = new UserSettingsMessage();
			
			try {
				UserLogic.getInstance().update(user);
			} catch (SettingsException e) {
				
				
				switch(e.getType()) {
					
					case 1 :
						usm.setName("podane imie jest niepoprawne!");
						break;
					case 2 :
						usm.setSurname("podane nazwisko jest niepoprawne!");
						break;
					case 3 :
						usm.setDescription("podany opis jest niepoprawne!");
						break;	
				}
				
			} catch (InvalidMailException e) {
				
				usm.setMail("podany mail nie jest poprawny!");
			}
			
			if(usm.error) request.setAttribute("message", usm);
			
			user = UserLogic.getInstance().getUser(user.getLogin());
			request.setAttribute("user", user);
			UserController.logIn(user, request.getSession());
			getServletContext().getRequestDispatcher("/WEB-INF/jsp/userSettings.jsp").forward(request, response);
			
		}
		else
			getServletContext().getRequestDispatcher("/WEB-INF/jsp/userSettings.jsp").forward(request, response);
		
	}

}
